<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCtime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="门店">
        <el-select v-model="queryParams.shopId" placeholder="请选择门店">
          <el-option
            v-for="item in shopList"
            :key="item.id"
            :label="item.shopName"
            :value="item.id"
            >
          </el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="供应商">
        <el-select v-model="queryParams.supplyId" placeholder="请选择供应商">
          <el-option
            v-for="item in supplyList"
            :key="item.supplyId"
            :label="item.sname"
            :value="item.supplyId"
            >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderlistList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司" align="center" prop="companyName" />
      <el-table-column label="门店" align="center" prop="shopName" />
      <el-table-column label="创建时间" align="center" prop="ctime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ctime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="送货时间" align="center" prop="acceptTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.acceptTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="送达时间" align="center" prop="arriveTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_list_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="结算状态" align="center" prop="ispay" >
        <template slot-scope="scope">
          <span v-if="scope.row.ispay == 0" class="el-tag el-tag--info">未结算</span>
          <span v-if="scope.row.ispay == 1" class="el-tag el-tag--success">已结算</span>
        </template>
      </el-table-column>
      <el-table-column label="供货商" align="center" prop="supplyName" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="发起人" align="center" prop="userName" />
      <el-table-column label="总价" align="center" prop="price" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="品类数量" align="center" prop="kind" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleLog(scope.row)"-->
<!--            v-hasRole="['company']"-->
<!--          >操作记录</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasRole="['company']"
          >详情</el-button>
          <el-button
            v-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleReview(scope.row)"
            v-hasRole="['company']"
          >审核</el-button>
          <el-button
            v-if="scope.row.status == 2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleConfirm(scope.row)"
            v-hasRole="['company']"
          >确认</el-button>
<!--          <el-button-->
<!--            v-if="scope.row.status == 3"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleReceive(scope.row)"-->
<!--            v-hasRole="['company']"-->
<!--          >确认收货</el-button>-->
          <el-button
            v-if="scope.row.status == 4"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEvaluate(scope.row)"
            v-hasRole="['company']"
          >评价</el-button>
<!--          <el-button-->
<!--            v-if="scope.row.status == 4 || scope.row.status == 5"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleEvaluate(scope.row)"-->
<!--            v-hasRole="['company']"-->
<!--          >退货</el-button>-->
          <el-button
            v-if="scope.row.status < 3"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasRole="['company']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status < 3"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasRole="['company']"
          >删除</el-button>
          <el-button
            v-if="scope.row.status < 3"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateDetail(scope.row)"
            v-hasRole="['company']"
          >编辑商品</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 退货对话框 -->
<!--    <el-dialog title="退货" :visible.sync="refundOpen" width="500px" append-to-body>-->


<!--    </el-dialog>-->

    <!-- 添加或修改采购单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">


        <el-form-item label="送货时间" prop="acceptTime">
          <el-date-picker clearable
                          :picker-options="{ disabledDate: disabledDate }"
                          v-model="form.acceptTime"
                          type="datetime"
                          default-time="10:00:00"
                          placeholder="请选择送货时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 确认收货对话框 -->
    <el-dialog :title="title" :visible.sync="receiveOpen" width="700px" append-to-body>
      <el-form ref="form" :model="receiveForm" :rules="rules" label-width="80px">
      <el-table :data="orderGoods" style="width: 100%">
        <el-table-column label="商品名称" prop="goodsName" />
        <el-table-column label="商品数量" prop="goodsNum" />
        <el-table-column label="实际数量" prop="goodsNumReal" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsNumReal" placeholder="请输入实际数量"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="goodsUnit"  label="单位" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_goods_unit" :value="scope.row.goodsUnit"/>
          </template>
        </el-table-column>
      </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormReceive">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="评分" :visible.sync="evaluateOpen" width="500px" append-to-body>
      <el-form ref="form" :model="evaluateForm" :rules="rules" label-width="80px">
        <el-form-item label="服务评分">
          <el-rate style="margin-top: 8px;" v-model="evaluateForm.starService" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
        </el-form-item>

        <el-form-item label="质量评分">
          <el-rate style="margin-top: 8px;" v-model="evaluateForm.starQuality" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
        </el-form-item>
        <el-form-item label="准时评分">
          <el-rate style="margin-top: 8px;" v-model="evaluateForm.starTimely" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormEvaluate">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { listOrderlist, getOrderlist, delOrderlist, addOrderlist, updateOrderlist,getOrderGoodsDetail ,receiveOrder,evaluate,formatDate} from "@/api/system/orderlist"
import { listSupply} from "@/api/system/supply"
import { listCompany,listShop} from "@/api/system/shop"

export default {
  name: "Orderlist",
  dicts: ['sys_list_status','sys_goods_unit'],
  data() {
    return {
      evaluateForm:{},//评分表单
      evaluateOpen:false,//评分弹窗
      //确认收货的订单商品列表
      orderGoods: [],
      //我的供货商列表
      supplyList: [],
      //公司列表
      companyList: [],
      //门店列表
      shopList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中的状态
      statuss:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购单表格数据
      orderlistList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 确认收货弹出层
      receiveOpen:false,
      //确认收货表单
      receiveForm:{},
      // 品类数量时间范围
      daterangeCtime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ctime: null,
        acceptTime: null,
        arriveTime: null,
        status: null,
        orderNo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  //获取焦点
  activated() {
    this.getList()
  },
  created() {
    this.getList()
    this.getSupplyList()
    this.getCompanyList()
    this.getShopList()
  },
  methods: {
    //限制时间
    disabledDate(time){
      return time.getTime() < (Date.now() -1000*60*60*24)
    },
    //提交评价
    submitFormEvaluate(){
      evaluate(this.evaluateForm).then(response => {
        this.$modal.msgSuccess("操作成功")
        this.evaluateOpen = false
        this.getList()
      })
    },
    //评价
    handleEvaluate(row){
      this.evaluateForm.id = row.id
      this.evaluateOpen = true
    },
    //订单详情
    handleDetail(row){
      this.$tab.openPage("采购单详情","/system/orderlist/info",{id:row.id})//打开新页面
      // let url = "/admin/listinfo?id="+row.id;
      // window.open(url);
    },
    //提交确认收货表单
    submitFormReceive(){
      this.receiveForm.goods = this.orderGoods
      receiveOrder(this.receiveForm).then(response => {
        this.$modal.msgSuccess("操作成功")
        this.receiveOpen = false
        this.getList()
      })
    },
    //确认收货,弹窗
    handleReceive(row){
      this.receiveOpen = true
      this.receiveForm = row
      this.orderGoods = []
      getOrderGoodsDetail(row.id).then(response => {
        // console.log("response:",response)
        this.orderGoods = response.rows
      })
    },
    //确认订单
    handleConfirm(row){
      //获取当前时间,格式为yyyy-MM-dd hh:mm:ss
      let now = new Date();
      let that = this;
      now = formatDate(now)
      this.$modal.confirm('是否确认订单编号为"' + row.id + '"的数据项？，确认后将无法在进行修改！').then(function() {
        updateOrderlist({id:row.id,status:3,confirmTime:now}).then(response => {
          that.$modal.msgSuccess("操作成功")
          that.getList()
        })
      })
    },
    //查看操作记录
    handleLog(row){

    },
    //审核
    handleReview(row){
      //获取当前时间,格式为yyyy-MM-dd hh:mm:ss
      let now = new Date();
      now = formatDate(now)
      updateOrderlist({id:row.id,status:1,reviewTime:now}).then(response => {
        this.$modal.msgSuccess("操作成功")
        this.getList()
      })
    },

    //获取公司列表
    getCompanyList(){
      listCompany({}).then(response => {
        this.companyList = response.rows
      })
    },

    //获取门店列表
    getShopList(){
      //清空门店列表
      this.shopList = []
      //获取当前选中的公司ID
      const companyId = this.form.companyId
      listShop({"companyId":companyId}).then(response => {
        this.shopList = response.rows
      })
    },

    //获取供应商列表
    getSupplyList(){
      listSupply({"status":"1"}).then(response => {
        this.supplyList = response.rows
      })
    },

    /** 查询采购单列表 */
    getList() {
      this.loading = true
      if (null != this.daterangeCtime && '' != this.daterangeCtime) {
        this.queryParams.params["beginCtime"] = this.daterangeCtime[0]
        this.queryParams.params["endCtime"] = this.daterangeCtime[1]
      }
      listOrderlist(this.queryParams).then(response => {
        this.orderlistList = response.rows
        this.total = response.total
        this.loading = false
        this.queryParams.params = {}
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.receiveOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        shopId: null,
        ctime: null,
        acceptTime: null,
        arriveTime: null,
        status: null,
        supplyId: null,
        orderNo: null,
        userId: null,
        price: null,
        remark: null,
        kind: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCtime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.statuss = selection.map(item => item.status)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //编辑商品
    handleUpdateDetail(row){
      // this.$router.push({path:"/system/orderlist/goodsEdit",query:{id:row.id}})//跳转

      this.$tab.openPage("商品编辑","/system/orderlist/goodsEdit",{id:row.id})//打开新页面
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.$router.push({path:"/system/orderlist/add"})//跳转
      this.$tab.openPage("新增采购单","/system/orderlist/add")//打开新页面
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrderlist(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改采购单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      let acceptTime = this.form.acceptTime
      this.form.acceptTime = formatDate(acceptTime)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrderlist(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrderlist(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log("delrow:",row)
      const ids = row.id || this.ids
      const status = row.status || this.statuss
      //判断状态
      for(let i=0;i<status.length;i++){
        if(status[i] >= 2){
          this.$modal.msgError("已确认的采购单不能删除！")
          return
        }
      }
      this.$modal.confirm('是否确认删除采购单编号为"' + ids + '"的数据项？').then(function() {
        return delOrderlist(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orderlist/export', {
        ...this.queryParams
      }, `orderlist_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
